package com.jsmtr.rms.utils;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jsmtr.rms.entity.BaseUser;
import com.jsmtr.rms.entity.NZResume;
import com.jsmtr.rms.service.ISysAdminService;
import com.jsmtr.rms.service.IUtilService;

/*权限拦截器*/
public class RightInterceptor implements HandlerInterceptor {

    @Resource
    private ISysAdminService sysAdminService;
    @Resource
    private IUtilService utilService;

    public final static String SEESION_MEMBER = "seesion_member";
    public final static String SEESION_RIGHT = "seesion_right";
    public final static String SEESION_NZVCODE = "seesion_nzvcode";
    public final static String SEESION_NZUSER = "seesion_nzuser";
    public final static String SEESION_USERVCODE = "seesion_uservocode";

    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

    }

    // 拦截spring-mvc.xml配置的路径的请求
    @SuppressWarnings("unchecked")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //根目录地址
        String contextPath = request.getContextPath();
        HttpSession session = request.getSession();
        //请求页面地址
        String spath = request.getServletPath();
        if (spath.startsWith("/NZ/")) {
            NZResume nzuser = (NZResume) session.getAttribute(SEESION_NZUSER);
            if (nzuser == null) {
                response.sendRedirect(contextPath + "/NZ/login");
                return false;
            }
        } else {
            //System.out.println("请求地址：" + request.getMethod() + ":" + spath);

            BaseUser user = (BaseUser) session.getAttribute(SEESION_MEMBER);
            if (user == null) {
                response.sendRedirect(contextPath + "/login");
                return false;
            } else {
                List<String> rights = (List<String>) session.getAttribute(SEESION_RIGHT);
                System.out.println(rights.contains("/Do/ZZSigning/"));
                if (rights.contains(spath)) {
                    return true;
                } else {
                    if (request.getMethod().equals("POST")) {
                        utilService.printJsonResult(false, "您没有访问权限，请联系管理员", "no", response);
                    } else {
                        response.sendRedirect(contextPath + "/illegal");
                    }
                    return false;
                }
            }
        }
        return true;
    }
}
